-
Notifications
You must be signed in to change notification settings - Fork 9
/
FolderExport+content.swift
79 lines (76 loc) · 3.12 KB
/
FolderExport+content.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
//
// FolderExport+content.swift
// Chord Provider
//
// © 2024 Nick Berendsen
//
import Foundation
import OSLog
import PDFKit
import ChordProShared
import SwiftlyChordUtilities
extension FolderExport {
/// Convert ChordPro files to a PDF
/// - Parameters:
/// - info: The document info for the PDF
/// - counter: The `PDFBuild.PageCounter` class
/// - options: The chord display options
/// - progress: A closure to observe the progress of PDF creation
/// - Returns: The PDF as `Data` and the `PageCounter` class with TOC info
static func content(
info: PDFBuild.DocumentInfo,
counter: PDFBuild.PageCounter,
songDisplayOptions: Song.DisplayOptions,
chordDisplayOptions: ChordDefinition.DisplayOptions,
progress: @escaping (Double) -> Void
) -> Data {
let builder = PDFBuild.Builder(info: info)
builder.pageCounter = counter
// MARK: Render PDF content
if let exportFolder = try? UserFileBookmark.getBookmarkURL(UserFileItem.exportFolder) {
/// Get access to the URL
_ = exportFolder.startAccessingSecurityScopedResource()
for item in counter.tocItems.sorted(using: KeyPathComparator(\.title)).sorted(using: KeyPathComparator(\.subtitle)) {
if let file = item.fileURL, let fileContents = try? String(contentsOf: file, encoding: .utf8) {
builder.elements.append(
PDFBuild.PageHeaderFooter(
header: [],
footer: [
PDFBuild.Section(
columns: [.flexible, .flexible],
items: [
PDFBuild.Text("\(item.subtitle)∙\(item.title)", attributes: .footer + .alignment(.left)),
counter
]
)
]
)
)
builder.elements.append(PDFBuild.PageBreak())
let song = ChordPro.parse(
id: item.id,
text: fileContents,
transpose: 0,
instrument: chordDisplayOptions.instrument,
fileURL: item.fileURL
)
builder.elements.append(
contentsOf: SongExport.getSongElements(
song: song,
chordDisplayOptions: chordDisplayOptions,
counter: counter
)
)
} else {
Logger.application.error("No Access to \(item.title, privacy: .public)")
}
}
/// Close access to the URL
exportFolder.stopAccessingSecurityScopedResource()
}
/// Generate the PDF
let content = builder.generatePdf { page in progress(page) }
/// Return content and counter
return content
}
}